package com.hs.sfzy.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.hs.sfzy.entity.Psych;
import com.hs.sfzy.entity.User;
import com.hs.sfzy.mapper.PsychMapper;
import com.hs.sfzy.mapper.UserMapper;
import com.hs.sfzy.service.PsychReplyService;
import com.hs.sfzy.service.PsychService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class PsychServiceImpl implements PsychService {
    @Autowired
    PsychMapper psychMapper;
    @Autowired
    private PsychReplyService psychReplyService;

    @Autowired
    private UserMapper userMapper;
    @Override
    public int insert(Psych psych) {
        int userId = psych.getUserId();
        User user = userMapper.findUserById(userId);
        user.setPoints(user.getPoints() + 10);
        userMapper.updateUser(user);
        return psychMapper.insert(psych);
    }

    @Override
    public int update(Psych psych) {
        return psychMapper.update(psych);
    }

    @Override
    public int delete(int id) {
        // 1. 先调用回复Service，批量删除该问题下的所有回复（处理1对多关联）
        psychReplyService.deleteByPsychId(id);
        // 2. 再调用问题Mapper，删除问题本身
        return psychMapper.delete(id); // 返回影响行数（>0表示成功
    }

    public Psych selectById(int id) {
        return psychMapper.selectById(id);
    }

    @Override
    public PageInfo<Psych> selectAll(int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<Psych> psyches = psychMapper.selectAll();
        for (Psych psych : psyches) {
            User user = userMapper.findUserById(psych.getUserId());
            psych.setUser(user);
        }
        return new PageInfo<>(psyches);
    }

    @Override
    public int incrementReplyCount(int psychId) {
        return psychMapper.incrementReplyCount(psychId);
    }
}
